package com.ysfxt.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ysfxt.exception.YsfxtException;
import com.ysfxt.mapper.EntryDocumentMapper;
import com.ysfxt.mapper.WorksFilesMapper;
import com.ysfxt.model.EntryDocument;
import com.ysfxt.model.SysTeacher;
import com.ysfxt.model.SysWorks;
import com.ysfxt.mapper.SysWorksMapper;
import com.ysfxt.model.WorksFiles;
import com.ysfxt.result.Result;
import com.ysfxt.result.ResultCodeEnum;
import com.ysfxt.service.SysWorksService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ysfxt.service.WorksFilesService;
import com.ysfxt.vo.ExcelWork;
import com.ysfxt.vo.FileVo;
import com.ysfxt.vo.SignUpVo;
import com.ysfxt.vo.WorksParam;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author ysfxt
 * @since 2024-03-29
 */
@Service
public class SysWorksServiceImpl extends ServiceImpl<SysWorksMapper, SysWorks> implements SysWorksService {
    
    @Resource
    private SysWorksMapper sysWorksMapper;
    
    @Resource
    private WorksFilesMapper worksFilesMapper;
    
    @Resource
    private EntryDocumentMapper entryDocumentMapper;
    
    @Resource
    private WorksFilesService worksFilesService;
    
    /**
     * 分页查询
     * @param worksParam
     * @return
     */
    @Override
    public Result select(WorksParam worksParam) {
        LambdaQueryWrapper<SysWorks> wrapper = new LambdaQueryWrapper<>();
        if(!StringUtils.isEmpty(worksParam.getCollege()))
            wrapper.like(SysWorks::getCollege, worksParam.getCollege());
        if(!StringUtils.isEmpty(worksParam.getWorksName()))
            wrapper.like(SysWorks::getWorksName, worksParam.getWorksName());
        if(!StringUtils.isEmpty(worksParam.getEntryName()))
            wrapper.like(SysWorks::getEntryName, worksParam.getEntryName());
        IPage<SysWorks> page = new Page(worksParam.getPageNum(),worksParam.getPageSize());
        sysWorksMapper.selectPage(page,wrapper);
        page.getRecords().stream().forEach(item->{
            item.setGroupString(item.getScope().getComment());
        });
        return Result.ok(page);
    }
    
    /**
     * 导出
     * @param response
     */
    @Override
    public void exportData(HttpServletResponse response) {
        try {
            //设置响应头信息和其他信息
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("UTF-8");
            String fileName = URLEncoder.encode("作品管理", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            //查询所有数据
            List<SysWorks> SysWorkss =sysWorksMapper.selectList(null);
            List<ExcelWork> excelWorks = new ArrayList<>();
            for (SysWorks s : SysWorkss) {
                ExcelWork e1 =new ExcelWork();
                e1.setId(s.getId());
                e1.setCollege(s.getCollege());
                e1.setScope(s.getScope().getComment());
                e1.setAvgScore(s.getAvgScore());
                e1.setWorksName(s.getWorksName());
                e1.setEntryName(s.getEntryName());
                e1.setGmtCreate(s.getGmtCreate());
                e1.setTelephone(s.getTelephone());
                excelWorks.add(e1);
            }
            //写出
            EasyExcel.write(response.getOutputStream(), ExcelWork.class)
                    .sheet("作品管理").doWrite(excelWorks);
        }catch (Exception e){
            e.printStackTrace();
            throw new YsfxtException(ResultCodeEnum.DATA_ERROR);
        }
    }
    
    /**
     * 查看详情
     * @param id
     * @return
     */
    @Override
    public Result getWorkInfo(Long id) {
        SysWorks work = sysWorksMapper.selectById(id);
        LambdaQueryWrapper<WorksFiles> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(WorksFiles::getWorksId, id);
        List<WorksFiles> worksFilesList = worksFilesMapper.selectList(wrapper);
        //文件类型   0:视频资料/课堂实录，1:教案，2:教学实施报告,3:专业人才培养方案，4:课程标准，5:其他附件/教材选用
        //根据文件类型分类
        Map<Integer, List<WorksFiles>> collect = worksFilesList.stream().collect(Collectors.groupingBy(item -> item.getType()));
        Map<String,Object> map = new HashMap<>();
        work.setPageViews(work.getPageViews()+1);
        sysWorksMapper.updateById(work);
        map.put("work",work);//作品简介部门：作品图品，作品名称、参赛学校、参赛老师、参赛组别、创建时间、浏览次数；
        map.put("worksFilesList",collect);//各种文件
        return Result.ok(map);
    }
    
    /**
     * 报名
     * @param signUpVo
     * @return
     */
    @Override
    public Result signUp(SignUpVo signUpVo) {
        SysWorks work =new SysWorks();
        //封装属性
        work.setCollege(signUpVo.getCollege());
        work.setScope(signUpVo.getGroup());
        work.setWorksName(signUpVo.getWorksName());
        work.setEntryName(signUpVo.getEntryName());
        work.setTelephone(signUpVo.getTelephone());
        work.setAvgScore(-1);
        work.setPageViews(0l);
        work.setGmtCreate(new Date());
        work.setGmtModified(new Date());
        sysWorksMapper.insert(work);
        //报名表
        EntryDocument entryForm = new EntryDocument();
        entryForm.setWorkId(work.getId());
        entryForm.setName(signUpVo.getEntryForm().getFileName());
        entryForm.setType(0);
        entryForm.setUrl(signUpVo.getEntryForm().getUrl());
        entryForm.setGmtCreate(new Date());
        entryForm.setGmtModified(new Date());
        //信息公示件
        EntryDocument infoMent = new EntryDocument();
        infoMent.setWorkId(work.getId());
        infoMent.setName(signUpVo.getInfoMent().getFileName());
        infoMent.setType(1);
        infoMent.setUrl(signUpVo.getInfoMent().getUrl());
        infoMent.setGmtCreate(new Date());
        infoMent.setGmtModified(new Date());
        entryDocumentMapper.insert(entryForm);
        entryDocumentMapper.insert(infoMent);
        
        /////////参赛作品
        List<FileVo> files = signUpVo.getFile();
        List<WorksFiles> works=new ArrayList<>();
        for (FileVo file : files) {
            WorksFiles works1 =new WorksFiles();
            works1.setWorksId(work.getId());
            works1.setName(file.getFileName());
            works1.setType(file.getType());
            works1.setTeam(file.getTeam());
            works1.setUrl(file.getUrl());
            works1.setGmtCreate(new Date());
            works1.setGmtModified(new Date());
            works.add(works1);
        }
        worksFilesService.saveBatch(works);
        return Result.ok();
    }
}
